#include "Puma.h"
#include <qfile.h>
#include <qtextstream.h>
#include <qapplication.h>

#include <iostream>
#include <QGLWidget>
#include <QMatrix4x4>
#include <QVector3D>
#include "qmessagebox.h"

#include <qmath.h>
namespace PUMA
{
	Puma::Puma(void)
	{
		buildGeometry();
	}


	Puma::~Puma(void)
	{
		qDeleteAll(parts);
	}

	void Puma::buildGeometry()
	{
		for(int i=1; i< 7; ++i)
		{
			QString fileName = QString("Meshes/mesh").append(QString::number(i)).append(".txt");
			QFile f(fileName);

			if( !f.open( QIODevice::ReadOnly) )
			{
				QMessageBox::warning(NULL, QString("Mesh loading failed!"),
					QString("File read error").append(fileName), QMessageBox::Ok,
                                QMessageBox::Ok);
				return;
			}

			QTextStream ts( &f );
			int num;
			ts >> num;

			QVector<QVector3D> tmpVertices;
			tmpVertices.reserve(num);
			for(int i= 0; i< num; ++i)
			{
				float x, y, z;
				ts >> x >> y >> z;
				tmpVertices.append(QVector3D(x,y,z));
			}
		
			ts >> num;
			Geometry * geom = new Geometry();
			for(int i= 0; i< num; ++i)
			{
				int ind;
				float x, y, z;
				ts >> ind >> x >> y >> z;
				geom->appendFaceted(tmpVertices[ind], QVector3D(x,y,z));
			}

			ts >> num;
			for(int i= 0; i< num; ++i)
			{
				int a,b,c;
				ts >> a >> b >> c;
				geom->appendTriangleIndices(a,b,c);
			}

			parts.append(new Patch(geom));
			f.close();
		}
	}

	void Puma::DrawShader(QGLShaderProgram& shaderProgram, QMatrix4x4& viewMatrix, QMatrix4x4& projectionMatrix)
	{
		Patch * p;
		foreach(p, parts)
		{
			p->draw(shaderProgram, viewMatrix, projectionMatrix);
		}
	}
}